#pragma once
#include <functional>
#include <string>
#include <unistd.h>
#include <sys/socket.h>
#include "Log.hpp"
#include "InetAddr.hpp"

using namespace LogMudule;
const static std::string defaultip="127.0.0.1";
const static int defaultport=8888;

using work_t=std::function<void(int)>;

class TCPClient
{
public:
    TCPClient(work_t work,std::string ip,uint16_t port):_work(work),_dst_addr({ip,port})
    {
        //创建套接字
        _sockfd=::socket(AF_INET,SOCK_STREAM,0);
        if(_sockfd<0)
        {
            LOG(LogLevel::FATAL)<<"socket failed";
            exit(1);
        }
        LOG(LogLevel::INFO)<<"socket succeed";
        //不需要绑定
    }
    void Run()
    {
        int n=::connect(_sockfd,_dst_addr.NetAddr(),_dst_addr.Len());
        if(n<0)
        {
            LOG(LogLevel::ERROR)<<"connect failed";
            exit(3);
        }
        LOG(LogLevel::INFO)<<"connect succeed";
        while(true)
        {
            _work(_sockfd);
        }
    }
    ~TCPClient()
    {
        ::close(_sockfd);
    }

private:
    int _sockfd;
    InetAddr _dst_addr;
    work_t _work;
};